package cn.tomoki.myapplication;

import android.content.Intent;
import android.view.View;
import android.widget.ImageButton;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.json.JSONArray;
import org.json.JSONObject;

import cn.tomoki.adapters.ListViewAdapter;
import cn.tomoki.beans.ItemBean;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.util.ArrayList;

//出库历史
public class OutHistoryActivity extends AppCompatActivity {
    private RecyclerView outHistoryView;
    private RefreshableView refreshableView;    //下拉刷新
    private ArrayList<ItemBean> mDate;
    private ListViewAdapter adapter;
    private static String userid;

    public OutHistoryActivity() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.out_history);

        //返回按钮
        ImageButton myBreak = findViewById(R.id.breakButton);
        myBreak.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //循环视图
        //找到控件
        outHistoryView = this.findViewById(R.id.outHistoryRecyclerView);
        refreshableView = this.findViewById(R.id.refreshableView);

        //设置样式
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        outHistoryView.setLayoutManager(layoutManager);
        //准备数据
        /**
         * 模拟数据
         */
        userid = "1";
        initDate();
        refreshableView.setOnRefreshListener(new RefreshableView.PullToRefreshListener() {
            @Override
            public void onRefresh() {
                try {
                    Thread.sleep(1000);
                    initDate(); //重新赋值
                    Utils.flush(outHistoryView);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(OutHistoryActivity.this, "刷新成功", Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(OutHistoryActivity.this, "刷新失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                refreshableView.finishRefreshing();
                Utils.finish(); //结束线程
            }
        }, 0);
    }

    private void initListener() {
        adapter.setOnItemClickListener(new ListViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                ItemBean itemBean = mDate.get(position);
                Intent intent = new Intent(OutHistoryActivity.this, OutHistoryDetalisActivity.class);
                intent.putExtra("mark", itemBean.getMark());
                intent.putExtra("back", itemBean.getBack());
                startActivity(intent);
            }
        });
    }

    /**
     * 这个方法用于初始化数据
     */
    private void initDate() {
        //创建数据集合
        mDate = new ArrayList<>();

        //接受后端数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    FormBody.Builder params = new FormBody.Builder();
                    params.add("userid", userid);
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url(Utils.classroomUrl+"/outuser/history")
                            .post(params.build())
                            .build();//创造http请求
                    Response response = client.newCall(request).execute();
                    String result = response.body().string();
                    JSONObject jsonObject = new JSONObject(result);
                    JSONArray jsonArray = new JSONArray(jsonObject.getString("history"));
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject object = jsonArray.getJSONObject(i);
                        String mark = object.getString("mark");
                        String time = object.getString("time");
                        String newTime = time.substring(0, time.indexOf(" "));   //截取到的时间
                        String name = object.getString("name");
                        String number = object.getString("number");
                        String back = object.getString("back");
                        ItemBean date = null;
                        //创建数据对象
                        date = new ItemBean(R.drawable.next, mark, userid, name, number, newTime, back);
                        mDate.add(date);
                        System.out.println(date);
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //创建适配器
                            adapter = new ListViewAdapter(mDate);
                            //设置到RecyclerView里头
                            outHistoryView.setAdapter(adapter);
                            //初始化事件
                            initListener();
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(OutHistoryActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }).start();
    }
}
